import VNode from '../../vdom/vnode.js'
import { getObjectValue } from '../../util/ObjectUtil.js'
/**
*创建v-for
*@param {Hue} vm 创建的Hue实例
*@param {dom} elm 虚拟节点对应的真实dom
*@param {VNode} parent 当前虚拟节点对应的父节点
*@param {string} instruction 指令内容
*/
export function vfor(vm, elm, parent, instruction) {
  //nodetype为0表示无用节点
  let virtualNode = new VNode(elm.nodeName, elm, [], parent, null, getInstructionValue(instruction)[2], 0)
  virtualNode.instruction = instruction
  parent.elm.removeChild(elm)
  parent.elm.appendChild(document.createTextNode(''))
  let values = getObjectValue(vm._data, getInstructionValue(instruction)[2])
  let creatDomList = []
  for (let i = 0; i < values.length; i++) {
    let env = initEnv(getInstructionValue(instruction)[0], values[i], i)
    let tempDom = document.createElement(elm.nodeName)
    tempDom.setAttribute('env', JSON.stringify(env))
    keepAttributes(elm, tempDom)
    tempDom.innerHTML = elm.innerHTML
    parent.elm.appendChild(tempDom)
    creatDomList.push(tempDom)
  }
  return virtualNode
}

/**
*继承原有属性
*@param {dom} elm 虚拟节点对应的真实dom
*@param {dom} newdom 新dom
*/
function keepAttributes(elm, newdom) {
  const attributenames = elm.getAttributeNames()
  for (const attributename of attributenames) {
    if (attributename.indexOf('v-bind:') === 0 || attributename.indexOf(':') === 0) {
      newdom.setAttribute(attributename, elm.getAttribute(attributename))
    } else if (attributename.indexOf('v-for') > -1) {
    } else {
      newdom.setAttribute(attributename, elm.getAttribute(attributename))
    }
  }
}

/**
*取出指令内容
*@param {string} instruction 指令内容, (key) in list
*/
function getInstructionValue(instruction) {
  let inset = instruction.trim().split(' ')
  if (inset.length !== 3 || (inset[1] !== 'in' && inset[1] !== 'of')) {
    console.log(inset)
    throw new Error('Error')
  }
  return inset
}

/**
*初始化环境变量
*@param {string} keyOrIndex (key) in list中前面部分
*@param {*} value key对应值
*@param {Number} index index对应值
*/
function initEnv(keyOrIndex, value, index) {
  return handleKeyOrIndex(keyOrIndex.trim(), value, index)
}

/**
*分理出key和index,并创造env
*@param {string} keyOrIndex (key) in list中前面部分
*@param {*} value key对应值
*@param {Number} index index对应值
*/
function handleKeyOrIndex(keyOrIndex, value, index) {
  let env = {}
  if (/\([a-zA-Z0-9.,_$]+\)/.test(keyOrIndex)) {
    keyOrIndex = keyOrIndex.substring(1, keyOrIndex.length - 1)
  }
  let handedValue = keyOrIndex.split(',')
  if (!handedValue) throw new Error('Error')
  if (handedValue.length >= 1) {
    env[handedValue[0]] = value
  }
  if (handedValue.length >= 2) {
    env[handedValue[1]] = index
  }
  return env
}